package com.hzjq.encrypt.ui

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import com.alibaba.fastjson.JSONObject
import com.hzjq.encrypt.AbsActivity
import com.hzjq.encrypt.R
import com.hzjq.encrypt.bean.EnBean
import com.hzjq.encrypt.encrypt.EncryptUtils
import com.hzjq.encrypt.pop.SqrqPop
import com.hzjq.encrypt.util.EToast
import com.hzjq.encrypt.util.KeyBoradX
import com.lxj.xpopup.XPopup
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_off_auth_layout.*
import kotlinx.android.synthetic.main.layout_en_info.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class OffAuthFileActivity : AbsActivity() {


    companion object {
        fun start(context: Context, who: Int) {
            val intent = Intent(context, OffAuthFileActivity::class.java)
            intent.putExtra("who", who)
            context.startActivity(intent)
        }
    }

    private val param = HashMap<String, String>()

    private var encrypt: EnBean? = null

    private var who = 0

    override fun onCreated() {
        who = intent.getIntExtra("who", 0)
        OkGo.getInstance().init(application)
        offPostResultLayout.visibility = View.GONE
        EventBus.getDefault().register(this)
        hideMore()
        setOnEncryptItemClick()
        offPostBtn.setOnClickListener {
            onSubmit()
        }
        when (who) {
            0 -> {
                offUidBhEtLayout.visibility = View.VISIBLE
            }
            1 -> {
                offUidBhEtLayout.visibility = View.GONE
            }
        }
    }

    override fun getContentViewId(): Int {
        return R.layout.activity_off_auth_layout
    }

    override fun getShowTitle(): String {
        when (who) {
            0 -> {
                return "在线下载授权"
            }
            1 -> {
                return "离线下载授权"
            }
        }
        return "离线下载授权"
    }

    private fun onSubmit() {
        if (TextUtils.isEmpty(offServerHttpEt.text)) {
            EToast.toast("请输入服务器地址")
            return
        }

        hideKeyBord()

        param["sbbh"] = if (TextUtils.isEmpty(offQbqBhEt.text)) "" else offQbqBhEt.text.toString()
        param["jd"] = if (TextUtils.isEmpty(offJdEt.text)) "" else offJdEt.text.toString()
        param["wd"] = if (TextUtils.isEmpty(offWdEt.text)) "" else offWdEt.text.toString()
        param["xmbh"] = if (TextUtils.isEmpty(offXmbhEt.text)) "" else offXmbhEt.text.toString()
        param["htid"] = if (TextUtils.isEmpty(offHtbhEt.text)) "" else offHtbhEt.text.toString()
        param["dwdm"] = if (TextUtils.isEmpty(offDwdmEt.text)) "" else offDwdmEt.text.toString()

        if (who == 0) {
            param["uid"] =
                if (TextUtils.isEmpty(offUidBhEt.text)) "" else offUidBhEt.text.toString()
        }

        val show = XPopup.Builder(this)
            .asLoading("正在请求中...")
            .show()
        val endocdeNoURL =
            EncryptUtils.endocdeNoURL(JSONObject.toJSONString(param), EncryptUtils.KEY_BASE)
        OkGo.post<String>(offServerHttpEt.text.toString())
            .params("param", endocdeNoURL)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    if (response != null) {
                        if (response.isSuccessful && !TextUtils.isEmpty(response.body())) {
                            val result =
                                EncryptUtils.decodeNoURL(response.body(), EncryptUtils.KEY_BASE)
                            val enBean = JSONObject.parseObject(result, EnBean::class.java)
                            runOnUiThread {
                                if (!TextUtils.equals("0", enBean.cwxx)) {
                                    offPostResultText.visibility = View.VISIBLE
                                    offPostResultLayout.visibility = View.GONE
                                    offPostResultText.text = EnBean.downloadError(enBean.cwxx)
                                } else {
                                    offPostResultText.visibility = View.GONE
                                    offPostResultLayout.visibility = View.VISIBLE
                                    enBean.filePath = "no path"
                                    EventBus.getDefault().post(enBean)
                                }
                            }
                        }
                    }
                }

                override fun onFinish() {
                    show.dismiss()
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    offPostResultText.visibility = View.VISIBLE
                    offPostResultLayout.visibility = View.GONE
                    offPostResultText.text = "请求错误\n${response?.exception}"
                }
            })
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun showEncrypt(encrypt: EnBean) {
        this.encrypt = encrypt
        encrypt.lgs?.let { encryptLg.text = it.lg.size.toString() + "发" }
        encrypt.jbqys?.let { encryptJb.text = it.jbqy.size.toString() + "个区域" }
        encrypt.zbqys?.let { encryptZb.text = it.zbqy.size.toString() + "个区域" }
        encrypt.sbbhs?.let { encryptQbq.text = it.size.toString() + "台起爆器" }
        encryptSqrq.text = encrypt.sqrq
    }


    private fun setOnEncryptItemClick() {
        encryptLg.setOnClickListener {
            hideKeyBord()
            LgEditorActivity.start(this, encrypt)
        }
        encryptJb.setOnClickListener {
            hideKeyBord()
            JbqyActivity.start(this, encrypt)
        }
        encryptZb.setOnClickListener {
            hideKeyBord()
            ZbqyActivity.start(this, encrypt)
        }
        encryptQbq.setOnClickListener {
            hideKeyBord()
            QbqActivity.start(this, encrypt)
        }
        encryptSqrq.setOnClickListener {
            hideKeyBord()
            SqrqPop.show(this, object : SqrqPop.OnSqrqEditorCallback {
                override fun onSqrqEditor(time: String) {
                    if (encrypt == null) {
                        encrypt = EnBean()
                    }
                    encrypt?.sqrq = time
                    if (encrypt != null) {
                        showEncrypt(encrypt!!)
                    }
                }
            }, if (encrypt == null) "" else encrypt!!.sqrq)
        }
    }


    private fun hideKeyBord() {
        KeyBoradX.hideKeyBoard(offServerHttpEt)
        KeyBoradX.hideKeyBoard(offQbqBhEt)
        KeyBoradX.hideKeyBoard(offJdEt)
        KeyBoradX.hideKeyBoard(offWdEt)
        KeyBoradX.hideKeyBoard(offHtbhEt)
        KeyBoradX.hideKeyBoard(offUidBhEt)
        KeyBoradX.hideKeyBoard(offXmbhEt)
        KeyBoradX.hideKeyBoard(offDwdmEt)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        hideKeyBord()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}